"""
豆瓣图书图片下载
"""
import os.path

from DrissionPage import ChromiumPage, ChromiumOptions
from DrissionPage import SessionPage


def download():
    dp = ChromiumOptions().set_paths(browser_path=r'C:\Program Files\Google\Chrome\Application\chrome.exe')
    page = ChromiumPage(dp)

    page.get('https://book.douban.com/tag/小说?start=0&type=T', retry=3, interval=2, timeout=15)

    for _ in range(2):
        for book in page.eles('x://li[@class="subject-item"]'):
            book_name = book.ele('x://h2/a').attr('title')
            img = book('x://img')
            img.save(path='./img/', name=f"{book_name}.png")
            print(f"{book_name}.png 保存成功!")

        # 点击下一页
        page('后页>').click()
        page.wait.load_start()

    page.close()


def headless_download():
    """ 无头模拟实现 """
    page = SessionPage()

    if not os.path.exists('./img'):
        os.mkdir('./img')

    for _ in range(2):
        page.get('https://book.douban.com/tag/小说?start={}&type=T'.format(_ * 20), retry=3, interval=2, timeout=15)
        for book in page.eles('x://li[@class="subject-item"]'):
            book_name = book.ele('x://h2/a').attr('title')
            img = book('x://img')
            img_url = img.attr('src')
            page.download.add(img_url, save_path='./img', rename=book_name + '.jpg')
            print(f"{book_name}.png 保存成功!")

    page.close()


if __name__ == '__main__':
    headless_download()
